package com.stox.client.ui.javafx.chartingy.model.shape;

import java.util.Date;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.Label;
import javafx.scene.shape.Line;

import com.stox.client.ui.javafx.chartingy.model.chart.Chart;
import com.stox.shared.util.Constant;

public class VerticalLine extends Shape {

	private final ControlPoint controlPoint;
	private final Line line = new Line();
	private final Label valueLabel = new Label();
	private final ChangeListener<Number> changeListener = new ChangeListener<Number>() {
		@Override
		public void changed(final ObservableValue<? extends Number> observable, final Number oldValue, final Number newValue) {
			controlPoint.setCenterY((line.getStartY() + line.getEndY()) / 2);
		}
	};

	public VerticalLine(final Chart<?, ?> chart, final double initialSceneX) {
		super(chart);
		controlPoint = new ControlPoint(chart) {
			@Override
			protected void dragToY(final double sceneX) {
				// No Op - User should not be able to drag it vertically
			}

			@Override
			public void update() {
				super.update();
				setCenterY((chart.getChartContentArea().getLayoutY() + chart.getChartContentArea().getHeight()) / 2);
			}
		};
		line.startXProperty().bindBidirectional(line.endXProperty());
		line.startXProperty().bindBidirectional(controlPoint.centerXProperty());
		line.startYProperty().bind(chart.getChartContentArea().layoutYProperty());
		line.endYProperty().bind(chart.getChartContentArea().layoutYProperty().add(chart.getChartContentArea().heightProperty()));
		deletePoint.centerXProperty().bindBidirectional(controlPoint.centerXProperty());
		deletePoint.centerYProperty().bind(line.startYProperty().add(deletePoint.radiusProperty()));
		valueLabel.layoutYProperty().bind(chart.primaryChart().getDateAxis().layoutYProperty());
		valueLabel.layoutXProperty().bind(controlPoint.centerXProperty().subtract(valueLabel.widthProperty().divide(2)));
		line.startYProperty().addListener(changeListener);
		line.endYProperty().addListener(changeListener);

		controlPoint.centerXProperty().addListener(new ChangeListener<Number>() {
			@Override
			public void changed(final ObservableValue<? extends Number> observable, final Number oldValue, final Number newValue) {
				valueLabel.setText(Constant.dateFormat.format(new Date(chart.primaryChart().getDateAxis().getValueForDisplay(newValue.doubleValue()))));
			}
		});

		final double mid = (chart.getChartContentArea().getLayoutY() + chart.getChartContentArea().getHeight()) / 2;
		controlPoint.setCenterY(mid);
		controlPoint.setCenterX(chart.getChartContentArea().sceneToLocal(initialSceneX, mid).getX());

		getChildren().addAll(line, controlPoint, deletePoint, valueLabel);
	}

	@Override
	public void update() {
		controlPoint.update();
	}

}
